package com.sudo.api.config;

import com.sudo.common.exception.BizException;
import com.sudo.common.utils.JsonRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.mail.MailSendException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

@Slf4j
@Order(9999)
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = Throwable.class)
    public JsonRes handler(Throwable e) {
        log.error("请求异常：",e);
        if(e instanceof BizException){
            return JsonRes.errorMsg(e.getMessage());
        } else if (e instanceof NullPointerException) {
            return JsonRes.errorMsg("发生空指针异常："+e);
        } else if (e instanceof IllegalArgumentException) {
            return JsonRes.errorMsg("请求参数类型不匹配："+e);
        } else if (e instanceof SQLException) {
            return JsonRes.errorMsg("数据库访问异常："+e);
        } else if (e instanceof MailSendException){
            return JsonRes.errorMsg("邮件发送失败，请检查邮箱是否可用");
        } else {
            return JsonRes.errorMsg("服务异常,请联系管理员："+e);
        }
    }
}
